// array转为utf-8 string

import moment from "moment";

export function blobByUtf8(blob){
  return new Promise((resolve, reject) => {
    try{
      blob.arrayBuffer().then((arrayBuffer) => {
        const view = new Uint8Array(arrayBuffer);
        resolve(JSON.parse(Utf8ArrayToStr(view)));
      })
    }catch (e) {
      reject(e)
    }
  })
}

function Utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = 0;
  while(i < len) {
    c = array[i++];
    switch(c >> 4)
    {
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
      // 0xxxxxxx
      out += String.fromCharCode(c);
      break;
      case 12: case 13:
      // 110x xxxx   10xx xxxx
      char2 = array[i++];
      out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
      break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
          ((char2 & 0x3F) << 6) |
          ((char3 & 0x3F) << 0));
        break;
    }
  }

  return out;
}

// 当前时间是否大于1小时
export function isOneH(d1, d2 = new Date()){
  if(!d1){
    return false
  }

  const dT1 = new Number(moment(d1,'YYYY-MM-DD HH:mm:ss').format('x'));
  const dT2 = new Number(moment(d2).format('x'));
  if(dT2 > ( dT1 - (1 * 60 * 60 * 1000))){
    return true
  }
  return false
}

// 设置Cookie
function setCookie(key, value, expiredays) {
  const exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie = `${key}=${escape(value)}${expiredays == null ? "" : `;expires=${exdate.toGMTString()}`}`;
}
// 获取Cookie
function getCookie(key) {
  const arrstr = document.cookie.split("; ");
  for (let i = 0; i < arrstr.length; i++) {
    const temp = arrstr[i].split("=");
    if (temp[0] == key) {
      return unescape(temp[1]);
    }
  }
}
// 清除Cookie
function delCookie(key) {
  const exdate = new Date();
  exdate.setTime(exdate.getTime() + -1 * 24 * 60 * 60 * 1000);
  const cookieVal = getCookie(key);
  document.cookie = `${key}=${cookieVal}; expires=${exdate.toGMTString()}`;
}
// function FindArrayFn(array, val) {
//   let obj = {};
//   for (let i = 0; i < array.length; i++) {
//     const ei = array[i];
//     if (ei.value == val) {
//       obj = ei;
//       break;
//     } else if (ei.children) {
//       obj = FindArrayFn(ei.children, val);
//     }
//   }
//   return obj;
// }
function FindArrayFn(array = [], val) {
  let obj = {};
  for (let i = 0; i < array.length; i++) {
    const ei = array[i];
    if (ei.value === val) {
      obj = ei;
    } else if (ei.children) {
      obj = FindArrayFn(ei.children, val);
    }
    if (JSON.stringify(obj) !== "{}") {
      break;
    }
  }
  return obj;
}
// 获取二级下拉菜单选中时的一级菜单和二级菜单数组
function getFirstAndSecondLevel(oriArr) {
  const obj = {
    firstLevel: [], // 一级菜单的集合
    secondLevel: [] // 二级菜单集合
  };
  for (let i = 0; i < oriArr.length; i++) {
    if (oriArr[i][0] && obj.firstLevel.indexOf(oriArr[i][0]) === -1) {
      obj.firstLevel.push(oriArr[i][0]);
    }
    if (oriArr[i][1] && obj.firstLevel.indexOf(oriArr[i][1]) === -1) {
      obj.secondLevel.push(oriArr[i][1]);
    }
  }
  return obj;
}
/**
 * 日期格式化
 * 使用 date | formatDate，默认格式yyyy-MM-dd HH:mm:ss
 * date | formatDate('yyyy年MM月dd日 HH:mm:ss')
 * @date 日期
 * @fmt 格式
 * @return 格式化后的日期
 */
const formatDateFn = function (date, fmt = "yyyy-MM-dd HH:mm:ss") {
  if (!date) {
    return "";
  }
  if (typeof date === "string") {
    date = date.replace("T", " ").replace("Z", "");
    date = new Date(date.replace(/-/g, "/"));
  }
  if (typeof date === "number") {
    date = new Date(date);
  }
  const o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
    "H+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  };
  const week = {
    0: "\u65e5",
    1: "\u4e00",
    2: "\u4e8c",
    3: "\u4e09",
    4: "\u56db",
    5: "\u4e94",
    6: "\u516d"
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, `${date.getFullYear()}`.substr(4 - RegExp.$1.length));
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[`${date.getDay()}`]
    );
  }
  for (const k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length));
    }
  }
  return fmt;
};
export function debounce(func, delay) {
  let timer; // 用于存储定时器的 ID

  return function(...args) {
    const context = this; // 保存当前的上下文 (this)

    // 每次事件触发时，清除之前的定时器
    if (timer) clearTimeout(timer);

    // 设置一个新的定时器，在 delay 毫秒后执行 func
    timer = setTimeout(() => {
      func.apply(context, args); // 执行传入的函数，并传递参数
    }, delay);
  };
}
export { getCookie, setCookie, delCookie, FindArrayFn, getFirstAndSecondLevel, formatDateFn };
